import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.ticker as mticker
#Change the following to the directory containing the Excel Data files
path='C:/Users/lenovo/Desktop/data'
sensitivity_df = pd.read_csv(path+'/sensitivity_analysis_results_observations.csv')

exchange_rate=0.15
sensitivity_df['swl']=sensitivity_df['swl']*sensitivity_df['deflator']*exchange_rate*10000/1000000
sensitivity_df['factor']=sensitivity_df['factor']-1

sfelist=["Heilongjiang Dahailin 2008","Heilongjiang Langxiang 1990","Heilongjiang Zhanhe 2000","Inner Mongolia Aershan 2000","Jilin Dunhua 2000"]
num_cols=len(sfelist)
def draw(sfelist, para, colname, df):
    # Filter dataframe
    filtered_df = df[(df['SFE'].isin(sfelist)) & (df['parameter'] == para)]
    
    if filtered_df.empty:
        print("No data available for the given parameters.")
        return

    if colname not in df.columns:
        print(f"Column '{colname}' not found in DataFrame.")
        return

    # Determine y-axis label and formatting
    y_label_map = {
        'x': r"SFE harvesting level ($m^3$)",
        'swl': r"Social welfare loss (million $)",
        'gamma': "SFE percentage of transfer"
    }

    # Determine x-axis label
    x_label_map = {
        'mu': r"Monitoring signal ($\eta$) percentage change",
        'xbar': r"Harvesting quota ($\bar{x}$) percentage change",
        'cp': "Harvesting cost (C) percentage change",
        'G': "Expenditure (G) percentage change",
        'P': "Timber price (P) percentage change",
        'alpha': r"Amenity parameter ($\alpha$) percentage change"
    }

    plt.figure(figsize=(10, 6))
    sns.lineplot(data=filtered_df, x='factor', y=colname, hue='SFE', style='SFE', markers=True)

    # Set axis labels
    plt.xlabel(x_label_map.get(para, rf'{para} percentage change'))
    plt.ylabel(y_label_map.get(colname, colname))

    # Format x-axis and y-axis as percentage if applicable
    plt.gca().xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x:.0%}'))
    if colname == 'gamma':
        plt.gca().yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x:.0%}'))
    elif colname in ['x', 'swl']:
        plt.gca().yaxis.set_major_formatter(mticker.ScalarFormatter(useMathText=True))
        plt.gca().ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
    # Adjust legend
    ncol = (len(sfelist) // 2) + (len(sfelist) % 2)
    plt.legend(title='SFE names', bbox_to_anchor=(0.5, -0.1), loc='upper center', ncol=ncol)
    
    plt.grid(True)

    # Save the plot
    plt.savefig(path+f'/{para}_{colname}.png', dpi=300, bbox_inches='tight')
    
    plt.show()


draw(sfelist,'mu','swl',sensitivity_df)
draw(sfelist,'xbar','swl',sensitivity_df)


draw(sfelist,'mu','x',sensitivity_df)
draw(sfelist,'xbar','x',sensitivity_df)


draw(sfelist,'mu','gamma',sensitivity_df)
draw(sfelist,'xbar','gamma',sensitivity_df)
draw(sfelist,'cp','gamma',sensitivity_df)
draw(sfelist,'P','gamma',sensitivity_df)
draw(sfelist,'G','gamma',sensitivity_df)



